package com.guomei.service.curse.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guomei.bean.ComputePriceResponse;
import com.guomei.bean.User;
import com.guomei.bean.curse.ComputePrice;
import com.guomei.bean.curse.Coupon;
import com.guomei.bean.curse.Course;
import com.guomei.bean.curse.CourseOrder;
import com.guomei.bean.curse.vo.CourseOrderDetail;
import com.guomei.mapper.UserMapper;
import com.guomei.mapper.curse.CourseMapper;
import com.guomei.mapper.curse.CourseOrderMapper;
import com.guomei.service.curse.CouponService;
import com.guomei.service.curse.CourseOrderService;
import com.guomei.service.curse.CourseService;
import com.guomei.service.curse.UserCouponService;
import com.guomei.utils.PageData;
import com.guomei.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 课程订单服务实现类
 */
@Service
@Slf4j
@Transactional
public class CourseOrderServiceImpl implements CourseOrderService {
    @Resource
    private CourseOrderMapper courseOrderMapper;

    @Resource
    private CouponService couponService;

    @Resource
    private CourseService courseService;
    @Resource
    private CourseMapper courseMapper;



    @Resource
    private UserCouponService userCouponService;
    @Autowired
    private UserMapper userMapper;

    @Override
    public CourseOrder getById(Long id) {
        if (id == null) {
            return null;
        }
        return courseOrderMapper.selectById(id);
    }

    @Override
    public CourseOrder getByOrderNo(String orderNo) {
        if (orderNo == null || orderNo.trim().isEmpty()) {
            return null;
        }
        return courseOrderMapper.selectByOrderNo(orderNo);
    }

    @Override
    public List<CourseOrder> getByUserId(Long userId, Short payStatus) {
        if (userId == null) {
            return null;
        }
        return courseOrderMapper.selectByUserId(userId, payStatus);
    }

    @Override
    public List<CourseOrder> getByCourseId(Long courseId) {
        if (courseId == null) {
            return null;
        }
        return courseOrderMapper.selectByCourseId(courseId);
    }

    @Override
    public List<CourseOrder> getAll() {
        return courseOrderMapper.selectAll();
    }

    @Override
    public Result<?> getByCondition(CourseOrder courseOrder) {
        PageHelper.startPage(courseOrder.getPageNum(), courseOrder.getPageSize());
        List<CourseOrder> courseOrders = courseOrderMapper.selectByCondition(courseOrder);
        // 封装分页结果到PageData
        PageData<CourseOrder> pageData = new PageData<>();
        PageInfo<CourseOrder> pageInfo = new PageInfo<>(courseOrders);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(courseOrder.getPageNum());
        pageData.setPageSize(courseOrder.getPageSize());
        return Result.success(pageData);
    }

    @Override
    public Result<?> getByConditionWithCourse(CourseOrder courseOrder) {
        PageHelper.startPage(courseOrder.getPageNum(), courseOrder.getPageSize());
        List<CourseOrder> courseOrders = courseOrderMapper.selectByConditionWithCourse(courseOrder);
        // 封装分页结果到PageData
        PageData<CourseOrder> pageData = new PageData<>();
        PageInfo<CourseOrder> pageInfo = new PageInfo<>(courseOrders);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(courseOrder.getPageNum());
        pageData.setPageSize(courseOrder.getPageSize());
        return Result.success(pageData);
    }

    @Override
    public List<CourseOrder> getByUserIdWithCourse(Long userId, Short payStatus) {
        if (userId == null) {
            return null;
        }
        return courseOrderMapper.selectByUserIdWithCourse(userId, payStatus);
    }

    @Override
    public List<CourseOrder> getExpiredUnpaidOrders() {
        return courseOrderMapper.selectExpiredUnpaidOrders();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> createOrder(CourseOrder courseOrder) {

        // 生成订单编号
        String orderNo = generateOrderNo();
        courseOrder.setOrderNo(orderNo);

        // 验证优惠券
        if (courseOrder.getCouponId() != null) {
            Coupon coupon = couponService.getById(courseOrder.getCouponId());
            if (coupon == null || !couponService.checkCouponAvailable(
                    courseOrder.getCouponId(), courseOrder.getCourseId(), courseOrder.getAmount())) {
                // 优惠券不可用
                return Result.fail("优惠券不可用");
            }
        }
        ComputePrice computePrice = new ComputePrice();
        computePrice.setCourseId(courseOrder.getCourseId());
        computePrice.setUserId(courseOrder.getUserId());
        computePrice.setCouponId(courseOrder.getCouponId());
        computePrice.setDistributionUserId(courseOrder.getDistributionUserId());
        Result<?> result = computePrice(computePrice);
        if (result.getData() != null){
            ComputePriceResponse computePriceResponse = (ComputePriceResponse) result.getData();
            if (computePriceResponse.getActualAmount().compareTo(courseOrder.getPayAmount()) != 0){
                // return Result.fail("创建订单->支付金额与计算价格不一致");
            }
        } else {
            return Result.fail("创建订单->计算订单价格失败");
        }

        // 设置默认值
        LocalDateTime now = LocalDateTime.now();
        courseOrder.setCreatedTime(now);
        courseOrder.setUpdatedTime(now);
        courseOrder.setPayStatus((short) 0); // 未支付

        // 设置订单过期时间，默认为24小时后
        if (courseOrder.getExpireTime() == null) {
            courseOrder.setExpireTime(now.plusHours(24));
        }

        // 保存订单
        if (courseOrderMapper.insert(courseOrder) > 0) {
            return Result.success("创建订单成功",courseOrder);
        }else {
            return Result.fail("创建订单失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSave(List<CourseOrder> orders) {
        if (orders == null || orders.isEmpty()) {
            return false;
        }

        LocalDateTime now = LocalDateTime.now();
        for (CourseOrder order : orders) {
            // 验证必填字段
            if (order.getUserId() == null || order.getCourseId() == null
                    || order.getAmount() == null || order.getPayAmount() == null) {
                return false;
            }

            // 生成订单编号
            order.setOrderNo(generateOrderNo());
            order.setCreatedTime(now);
            order.setUpdatedTime(now);

            // 设置默认支付状态
            if (order.getPayStatus() == null) {
                order.setPayStatus((short) 0);
            }

            // 设置默认过期时间
            if (order.getExpireTime() == null) {
                order.setExpireTime(now.plusHours(24));
            }
        }

        return courseOrderMapper.batchInsert(orders) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> update(CourseOrder courseOrder) {
        if (courseOrder == null || courseOrder.getId() == null) {
            return Result.fail("参数错误");
        }

        courseOrder.setUpdatedTime(LocalDateTime.now());
        return courseOrderMapper.updateById(courseOrder) > 0 ? Result.success("更新订单成功") : Result.fail("更新失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderStatus(String orderNo, Short payStatus, Short payType) {
        if (orderNo == null || orderNo.trim().isEmpty() || payStatus == null) {
            return false;
        }

        // 检查订单是否存在
        CourseOrder order = getByOrderNo(orderNo);
        if (order == null) {
            return false;
        }

        // 如果是支付操作，更新支付时间
        LocalDateTime payTime = (payStatus == 1) ? LocalDateTime.now() : null;

        // 更新订单状态
        int rows = courseOrderMapper.updateStatusByOrderNo(orderNo, payStatus, payType, payTime);

        // 如果是支付成功，更新优惠券使用数量
        if (rows > 0 && payStatus == 1 && order.getCouponId() != null) {
            couponService.updateUsedCount(order.getCouponId(), 1);
        }

        return rows > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderStatus(String orderNo, Short payStatus, Short payType, Short orderStatus) {
        if (orderNo == null || orderNo.trim().isEmpty() || payStatus == null) {
            return false;
        }

        // 检查订单是否存在
        CourseOrder order = getByOrderNo(orderNo);
        if (order == null) {
            return false;
        }

        // 如果是支付操作，更新支付时间
        LocalDateTime payTime = (payStatus == 1) ? LocalDateTime.now() : null;

        // 更新订单状态（包含订单状态）
        int rows = courseOrderMapper.updateStatusByOrderNoWithOrderStatus(orderNo, payStatus, payType, payTime, orderStatus);

        // 如果是支付成功，更新优惠券使用数量
        if (rows > 0 && payStatus == 1 && order.getCouponId() != null) {
            couponService.updateUsedCount(order.getCouponId(), 1);
        }

        return rows > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateWxNoByOrderNo(String orderNo, String wxNo) {
        if (orderNo == null || orderNo.trim().isEmpty() || wxNo == null || wxNo.trim().isEmpty()) {
            log.warn("参数错误: orderNo={}, wxNo={}", orderNo, wxNo);
            return false;
        }

        // 检查订单是否存在
        CourseOrder order = getByOrderNo(orderNo);
        if (order == null) {
            log.warn("订单不存在: orderNo={}", orderNo);
            return false;
        }

        int rows = courseOrderMapper.updateWxNoByOrderNo(orderNo, wxNo);
        if (rows > 0) {
            log.info("成功更新订单微信交易号: orderNo={}, wxNo={}", orderNo, wxNo);
        } else {
            log.warn("更新订单微信交易号失败: orderNo={}, wxNo={}", orderNo, wxNo);
        }
        return rows > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateWechatPayStatus(String orderNo, Short payStatus, Short payType, LocalDateTime payTime, String transactionId) {
        if (orderNo == null || orderNo.trim().isEmpty() || payStatus == null) {
            log.warn("参数错误: orderNo={}, payStatus={}", orderNo, payStatus);
            return false;
        }

        // 检查订单是否存在
        CourseOrder order = getByOrderNo(orderNo);
        if (order == null) {
            log.warn("订单不存在: orderNo={}", orderNo);
            return false;
        }

        // 防止重复支付
        if (order.getPayStatus() != null && order.getPayStatus() == 1) {
            log.warn("订单已支付，跳过处理: orderNo={}", orderNo);
            return true;
        }

        int rows = courseOrderMapper.updateWechatPayStatus(orderNo, payStatus, payType, payTime, transactionId);

        // 如果是支付成功，更新优惠券使用数量
        if (rows > 0 && payStatus == 1 && order.getCouponId() != null) {
            couponService.updateUsedCount(order.getCouponId(), 1);
        }

        if (rows > 0) {
            log.info("微信支付状态更新成功: orderNo={}, payStatus={}, transactionId={}", orderNo, payStatus, transactionId);
        } else {
            log.warn("微信支付状态更新失败: orderNo={}, payStatus={}, transactionId={}", orderNo, payStatus, transactionId);
        }
        return rows > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(String orderNo) {
        return updateOrderStatus(orderNo, (short) 2, null, (short) 2); // 订单状态也设为已取消
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void autoCancelExpiredOrders() {
        List<CourseOrder> expiredOrders = getExpiredUnpaidOrders();
        if (expiredOrders != null && !expiredOrders.isEmpty()) {
            for (CourseOrder order : expiredOrders) {
                cancelOrder(order.getOrderNo());
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Long id) {
        if (id == null) {
            return false;
        }
        return courseOrderMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchRemove(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return courseOrderMapper.batchDelete(ids) > 0;
    }

    @Override
    public Result<?> computePrice(ComputePrice computePrice) {
        //实际支付金额
        BigDecimal actualAmount = BigDecimal.ZERO;;
        //优惠卷优化金额
        BigDecimal deductionAmount = BigDecimal.ZERO;;
        //先获取课程金额和优惠金额  得出实际课程价格
        Long courseId = computePrice.getCourseId();
        Course course = courseService.getById(courseId);
        if (course == null || course.getPrice().compareTo(BigDecimal.ZERO) <= 0){
            log.info("课程不存在或价格小于等于0");
            return Result.fail("课程不存在或价格小于等于0");
        }
        actualAmount = course.getPrice().subtract(course.getSalePrice());

        if (computePrice.getCouponId() != null && computePrice.getCouponId() !=null) {
            Coupon coupon = couponService.getById(computePrice.getCouponId());
            if (coupon == null || !couponService.checkCouponAvailable(
                    computePrice.getCouponId(), courseId, actualAmount)) {
                // 优惠券不可用
                log.info("优惠券不可用");
                return Result.fail("优惠券不可用");
            }
            //验证用户是否存在该优惠券
            if (!userCouponService.checkUserHasCoupon(computePrice.getUserId(), computePrice.getCouponId())){
                log.info("用户该优惠券不存在/已使用/已失效");
                return Result.fail("用户该优惠券不存在/已使用/已失效");
            }
            //满减卷
            if (coupon.getCouponType() == 1){
                deductionAmount = coupon.getDiscountValue();
                actualAmount = actualAmount.subtract(coupon.getDiscountValue());
                // 检查实际支付金额是否小于0
                if (actualAmount.compareTo(BigDecimal.ZERO) < 0) {
                    log.info("优惠券抵扣金额超过课程价格");
                    return Result.fail("优惠券抵扣金额超过课程价格");
                }
            }
            //折扣卷
            if (coupon.getCouponType() == 2){
                actualAmount = actualAmount.multiply(coupon.getDiscountValue().divide(new BigDecimal("100")));
                deductionAmount = course.getPrice().subtract(actualAmount);
                // 检查实际支付金额是否小于0
                if (deductionAmount.compareTo(BigDecimal.ZERO) < 0) {
                    log.info("优惠券抵扣金额超过课程价格");
                    return Result.fail("优惠券抵扣金额超过课程价格");
                }
            }
        }
        ComputePriceResponse response = new ComputePriceResponse();
        response.setActualAmount(actualAmount);
        response.setDeductionAmount(deductionAmount);

        //分销金额和分销人  暂时留空-----------------------

        return Result.success(response);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean softDeleteOrder(String orderNo) {
        if (orderNo == null || orderNo.trim().isEmpty()) {
            log.warn("订单号不能为空");
            return false;
        }
        
        try {
            CourseOrder order = getByOrderNo(orderNo);
            if (order == null) {
                log.warn("订单不存在: orderNo={}", orderNo);
                return false;
            }
            
            // 设置软删除标志
            order.setIsDeleted(true);
            order.setUpdatedTime(LocalDateTime.now());
            
            int result = courseOrderMapper.updateById(order);
            if (result > 0) {
                log.info("软删除订单成功: orderNo={}", orderNo);
                return true;
            } else {
                log.warn("软删除订单失败: orderNo={}", orderNo);
                return false;
            }
            
        } catch (Exception e) {
            log.error("软删除订单异常: orderNo={}", orderNo, e);
            return false;
        }
    }

    @Override
    public Result<?> getByConditionWithCourseCount(CourseOrder courseOrder) {
        List<User> users = new ArrayList<>();
        List<CourseOrder> courseOrders = new ArrayList<>();
        BigDecimal countFee = BigDecimal.ZERO;
        //分销人员的统计
        if (courseOrder.getDistributionUserId() != null && !courseOrder.getDistributionUserId().isEmpty()
        && courseOrder.getCountType().equals("1")){
            users = userMapper.selectByParentId(Long.valueOf(courseOrder.getDistributionUserId()));
            PageHelper.startPage(courseOrder.getPageNum(), courseOrder.getPageSize());
            CourseOrder courseOrder2 = new CourseOrder();
            courseOrder2.setDistributionUserId(courseOrder.getDistributionUserId());
            courseOrder2.setPayStatus(Short.valueOf("1"));
            courseOrders = courseOrderMapper.selectByCondition1(courseOrder2);
            if (courseOrders != null && !courseOrders.isEmpty()){
                for (CourseOrder courseOrder1 : courseOrders) {
                    if (courseOrder1.getDistributionAmount() != null){
                        countFee = courseOrder1.getDistributionAmount().add(countFee);
                    }
                    Course course = courseMapper.selectById(courseOrder1.getCourseId());
                    courseOrder1.setCourseName(course.getCourseName());
                }
            }
            //根据总管理员统计
        }else if (courseOrder.getCountType().equals("2")){
            users = userMapper.selectByParentIdAll();
            CourseOrder courseOrder2 = new CourseOrder();
            courseOrder2.setPayStatus(Short.valueOf("1"));
            PageHelper.startPage(courseOrder.getPageNum(), courseOrder.getPageSize());
            courseOrders = courseOrderMapper.selectByCondition1(null);
            if (courseOrders != null && !courseOrders.isEmpty()){
                for (CourseOrder courseOrder1 : courseOrders) {
                    if (courseOrder1.getDistributionAmount() != null){
                        countFee = courseOrder1.getDistributionAmount().add(countFee);
                    }
                    Course course = courseMapper.selectById(courseOrder1.getCourseId());
                    courseOrder1.setCourseName(course.getCourseName());
                }
            }
        } else if (courseOrder.getTeacherId() != null && !courseOrder.getTeacherId().toString().isEmpty()
                && courseOrder.getCountType().equals("3")) {
            CourseOrder courseOrder2 = new CourseOrder();
            Course course = new Course();
            ArrayList<Long> courseList = new ArrayList<>();
            course.setTeacherId(courseOrder.getTeacherId());
            List<Course> courses = courseMapper.selectByCondition(course);
            for (Course cours : courses) {
                courseList.add(cours.getId());
            }
            courseOrder2.setCourseIds(courseList);
            courseOrder2.setPayStatus(Short.valueOf("1"));
            PageHelper.startPage(courseOrder.getPageNum(), courseOrder.getPageSize());
            courseOrders = courseOrderMapper.selectByCondition1(courseOrder2);

            if (courseOrders != null && !courseOrders.isEmpty()){
                for (CourseOrder courseOrder1 : courseOrders) {
                    if (courseOrder1.getDistributionAmount() != null){
                        countFee = courseOrder1.getDistributionAmount().add(countFee);
                    }
                    Course coursez = courseMapper.selectById(courseOrder1.getCourseId());
                    courseOrder1.setCourseName(coursez.getCourseName());
                }
            }
            users = userMapper.selectByParentId(courseOrder.getTeacherId());
        }
        // 封装分页结果到PageData
        PageData<CourseOrder> pageData = new PageData<>();
        PageInfo<CourseOrder> pageInfo = new PageInfo<>(courseOrders);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(courseOrder.getPageNum());
        pageData.setPageSize(courseOrder.getPageSize());
        pageData.setCountInviteCount(users.size());
        pageData.setCountdistributionAmount(countFee);
        pageData.setCountOrderCount(courseOrders.size());

        return Result.success(pageData);
    }

    @Override
    public Result<?> getByCourseList(CourseOrder order) {
        if (order == null || (order.getCourseIds() == null || order.getCourseIds().isEmpty())){
            return Result.fail("参数存在错误，请检查参数");
        }
        PageHelper.startPage(order.getPageNum(), order.getPageSize());
        List<CourseOrder> courseOrders = courseOrderMapper.selectByCourseList(order);
        if (courseOrders != null && !courseOrders.isEmpty()){
            for (CourseOrder courseOrder : courseOrders) {
                User user = userMapper.selectById(courseOrder.getUserId());
                courseOrder.setUser(user);
            }
        }
        // 封装分页结果到PageData
        PageData<CourseOrder> pageData = new PageData<>();
        PageInfo<CourseOrder> pageInfo = new PageInfo<>(courseOrders);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(order.getPageNum());
        pageData.setPageSize(order.getPageSize());
        return Result.success(pageData);
    }

    @Override
    public Result<?> selectTeacherOrder(User user) {
        List<CourseOrder> courseOrders = new ArrayList<>();
        if (user == null || user.getId() == null){
            return Result.fail("老师id不存在，请检查参数");
        }

        PageHelper.startPage(user.getPageNum(), user.getPageSize());
        // 封装分页结果到PageData
        List<Course> courses = courseMapper.selectCourseWithOrdersByTeacherId(user.getId(),user.getPayStatus());
        PageData<Course> pageData = new PageData<>();
        PageInfo<Course> pageInfo = new PageInfo<>(courses);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(user.getPageNum());
        pageData.setPageSize(user.getPageSize());
        return Result.success(pageData);

    }

    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        // 订单编号规则：时间戳 + 随机数
        String timestamp = String.valueOf(System.currentTimeMillis());
        String random = String.format("%04d", new Random().nextInt(10000));
        return timestamp + random;
    }

    @Override
    public Result<?> getOrderDetail(String orderNo) {
        if (orderNo == null || orderNo.trim().isEmpty()) {
            return Result.fail("订单号不能为空");
        }
        CourseOrder order = getByOrderNo(orderNo);
        if (order == null) {
            return Result.fail("订单不存在");
        }
        CourseOrderDetail orderDetail = new CourseOrderDetail();

        Course course = courseMapper.selectById(order.getCourseId());
        User buyUser = userMapper.selectById(order.getUserId());
        User teacher = userMapper.selectById(course.getTeacherId());
        if (order.getDistributionUserId() != null && !order.getDistributionUserId().isEmpty()) {
            User distributionUser = userMapper.selectById(Long.valueOf(order.getDistributionUserId()));
            if (distributionUser != null) {
                orderDetail.setDistributionUser(distributionUser);
            }

        }
        orderDetail.setCourseOrder(order);
        orderDetail.setCourse(course);
        orderDetail.setBuyUser(buyUser);
        orderDetail.setTeacher(teacher);

        return Result.success(orderDetail);
    }
}
